package com.ztsoft.user.service.user.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ztsoft.user.mapper.user.SysRoleMapper;
import com.ztsoft.user.pojo.entity.user.SysMenu;
import com.ztsoft.user.pojo.entity.user.SysRole;
import com.ztsoft.user.pojo.entity.user.SysRoleMenu;
import com.ztsoft.user.pojo.entity.user.SysUserRole;
import com.ztsoft.user.pojo.enums.ResultCode;
import com.ztsoft.user.pojo.vo.user.SysRoleVo;
import com.ztsoft.user.pojo.vo.user.SysRoleVoTree;
import com.ztsoft.user.service.user.SysMenuService;
import com.ztsoft.user.service.user.SysRoleMenuService;
import com.ztsoft.user.service.user.SysRoleService;
import com.ztsoft.user.service.user.SysUserRoleService;
import com.ztsoft.user.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Resource
    private SysRoleMenuService sysRoleMenuService;
    @Resource
    private SysMenuService sysMenuService;
    @Resource
    private SysUserRoleService sysUserRoleService;

    @Override
    public Result<Object> queryRole() {
        Map<String, Object> resultMap = new HashMap<>();
        List<SysRoleVoTree> sysRoleVoTreeList = new ArrayList<>();
        // 查询角色基本信息
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        List<SysRole> sysRoleList = this.list(queryWrapper);

        for (SysRole sysRole : sysRoleList) {
            SysRoleVoTree sysRoleVoTree = new SysRoleVoTree();
            sysRoleVoTree.setValue(sysRole.getRoleId());
            sysRoleVoTree.setLabel(sysRole.getRoleName());
            sysRoleVoTreeList.add(sysRoleVoTree);
        }

        resultMap.put("result", sysRoleVoTreeList);
        return Result.success(resultMap);
    }

    @Override
    public Result<Object> queryRoleByPage(SysRole role, Integer currentPage, Integer pageSize) {
        try {
            // 查询角色基本信息
            List<SysMenu> menuList = new ArrayList<>();
            Map<String, Object> resultMap = new HashMap<>();
            QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>(role);
            queryWrapper.orderByAsc("role_sort");
            IPage<SysRole> page = this.page(new Page<>(currentPage, pageSize), queryWrapper);

            List<SysRoleVo> list = JSON.parseArray(JSON.toJSONString(page.getRecords()), SysRoleVo.class);

            // 组装角色的菜单信息
            for (SysRoleVo sysRoleVo : list) {
                // 查询角色拥有菜单
                QueryWrapper<SysRoleMenu> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("role_id", sysRoleVo.getRoleId());
                List<SysRoleMenu> sysRoleMenuList = sysRoleMenuService.list(queryWrapper2);

                List<String> menuIds = new ArrayList<>();
                for (SysRoleMenu sysRoleMenu : sysRoleMenuList) {
                    menuIds.add(sysRoleMenu.getMenuId());
                    menuList.add(sysMenuService.getById(sysRoleMenu.getMenuId()));
                }

                sysRoleVo.setIsStatus(this.getById(sysRoleVo.getRoleId()).getStatus() == 1);
                sysRoleVo.setMenuIds(menuIds.toArray(new String[0]));
                sysRoleVo.setMenuList(menuList);
            }

            resultMap.put("total", page.getTotal());
            resultMap.put("result", list);
            return Result.success(resultMap);
        } catch (Exception e) {
            log.error("出现异常", e);
            return Result.fail();
        }
    }

    @Override
    public Result<Object> addRole(SysRoleVo sysRoleVo) {
        SysRole role = BeanUtil.copyProperties(sysRoleVo, SysRole.class);

        QueryWrapper<SysRole> sysRoleQueryWrapper = new QueryWrapper<>();
        sysRoleQueryWrapper.eq("role_name", role.getRoleName());
        SysRole sysRole = getOne(sysRoleQueryWrapper);

        if (ObjectUtil.isNotNull(sysRole)) {
            return Result.returnMsg("数据库已经存在相同角色名称数据，添加失败！", ResultCode.FAILED.getCode());
        }

        role.setStatus(Boolean.TRUE.equals(sysRoleVo.getIsStatus()) ? 1 : 2);
        boolean isSuccess = this.save(role);
        if (isSuccess) {
            return Result.success();
        }
        return Result.fail();
    }

    @Override
    public Result<Object> updateRoleInfo(SysRoleVo sysRoleVo) {
        SysRole role = BeanUtil.copyProperties(sysRoleVo, SysRole.class);
        role.setStatus(Boolean.TRUE.equals(sysRoleVo.getIsStatus()) ? 1 : 2);
        boolean isSuccess = this.updateById(role);
        if (isSuccess) {
            return Result.success();
        }
        return Result.fail();
    }

    @Override
    public Result<Object> updateRoleAndMenu(SysRoleVo sysRoleVo) {
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("role_id", sysRoleVo.getRoleId());
        sysRoleMenuService.removeByMap(queryMap);

        String[] menuIds = sysRoleVo.getMenuIds();
        for (String menuId : menuIds) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(sysRoleVo.getRoleId());
            sysRoleMenu.setMenuId(menuId);
            sysRoleMenuService.save(sysRoleMenu);
        }

        SysRole role = BeanUtil.copyProperties(sysRoleVo, SysRole.class);

        boolean isSuccess = this.updateById(role);
        if (isSuccess) {
            return Result.success();
        }
        return Result.fail();
    }

    @Override
    public Result<Object> deleteRole(String id) {
        QueryWrapper<SysRoleMenu> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("role_id", id);
        List<SysRoleMenu> sysRoleMenuList = sysRoleMenuService.list(queryWrapper2);
        for (SysRoleMenu sysRoleMenu : sysRoleMenuList) {
            Map<String, Object> removeMap = new HashMap<>();
            removeMap.put("role_id", sysRoleMenu.getRoleId());
            removeMap.put("menu_id", sysRoleMenu.getMenuId());
            sysRoleMenuService.removeByMap(removeMap);
        }
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("role_id", id));
        boolean isSuccess = this.removeById(id);
        if (isSuccess) {
            return Result.success();
        }
        return Result.fail();
    }

    @Override
    public Result<Object> queryAllRoleName() {
        // 查询角色基本信息
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1).select("DISTINCT role_name");
        List<SysRole> sysRoleList = this.list(queryWrapper);

        List<String> roleNameList = new ArrayList<>();
        sysRoleList.forEach(sysRole -> roleNameList.add(sysRole.getRoleName()));

        return Result.success(roleNameList);
    }

}